package com.simpleplayer.contentview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

import com.simpleplayer.services.LogUtil;

@SuppressLint("ViewConstructor")
class ContentSurfaceView extends SurfaceView
        implements SurfaceHolder.Callback, ContentView {

    private static final String TAG = "VideoSurfaceView";

    private final SurfaceListener mSurfaceListener;

    private int mContentWidth = 0;
    private int mContentHeight = 0;

    public ContentSurfaceView(Context context, SurfaceListener listener) {
        super(context);
        this.mSurfaceListener = listener;
        setBackgroundColor(Color.argb(50, 50, 50, 50));

        if (listener != null) {
            getHolder().addCallback(this);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 1;
        int height = 1;
        if (mContentWidth > 0 && mContentHeight > 0) {
            width = getDefaultSize(mContentWidth, widthMeasureSpec);
            height = getDefaultSize(mContentHeight, heightMeasureSpec);
            if (mContentWidth * height  > width * mContentHeight) {
                height = width * mContentHeight / mContentWidth;
            } else if (mContentWidth * height  < width * mContentHeight) {
                width = height * mContentWidth / mContentHeight;
            }
        }
        setMeasuredDimension(width, height);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        mSurfaceListener.onSurfaceHolderCreate(holder);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        LogUtil.d(TAG, "surfaceChanged (" + width + ", " + height + ")");
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        // do nothing
    }

    @Override
    public void onContentSizeChanged(int width, int height) {
        // ignore size 0, it's meaningless
        if (width == 0 || height == 0)
            return;
        if (mContentWidth != width || mContentHeight != height) {
            mContentWidth = width;
            mContentHeight = height;
            getHolder().setFixedSize(mContentWidth, mContentHeight);
            requestLayout();
        }
    }

    @NonNull
    @Override
    public SurfaceView getView() {
        return this;
    }
}
